#!/usr/bin/env python
"""
新版 SecureConfigManager CLI 演示脚本
演示如何通过 Python 调用 secureconfig 命令行工具，操作 json、text、binary 三类文件。
还展示了如何使用 --inplace 参数进行原地加解密。
"""
import subprocess
import json
import os
import sys
import time
import shutil

def run_secureconfig_command(command, *args, format="json"):
    """
    执行 secureconfig 命令并返回结果
    """
    full_command = ["secureconfig"]
    full_command.append(command)
    full_command.extend(list(args))
    try:
        print("正在执行命令: ", " ".join(full_command))
        result = subprocess.run(full_command, capture_output=True, text=True, check=True)
        if format == "json":
            json_output = result.stdout
            json_start = json_output.find('{')
            if json_start >= 0:
                json_output = json_output[json_start:]
            return json.loads(json_output)
        return {"output": result.stdout.strip()}
    except subprocess.CalledProcessError as e:
        error_message = e.stderr or "未知错误"
        return {"status": "error", "message": error_message}
    except Exception as e:
        return {"status": "error", "message": str(e)}


def print_result(title, result):
    print(f"\n==== {title} ====")
    if result.get("status") == "success":
        print(json.dumps(result, ensure_ascii=False, indent=4))
    else:
        print(f"失败: {result.get('message')}")

if __name__ == "__main__":
    total_start_time = time.time()

    print("\n===== 第一部分: 常规加解密操作 =====")

    # 1. 创建 json 配置文件
    json_name = "demo_json"
    print(f"创建 json 配置文件: {json_name}")
    result = run_secureconfig_command("create", json_name, "--type", "json", "--force")
    print_result("创建 json 配置", result)

    # 2. set-value 仅支持 json
    print(f"设置 json 配置的值: {json_name} app.version = 2.0.0")
    result = run_secureconfig_command("set-value", json_name, "app.version", "2.0.0")
    print_result("设置 json 配置值", result)

    # 3. get-value 仅支持 json
    print(f"获取 json 配置的值: {json_name} app.version")
    result = run_secureconfig_command("get-value", json_name, "app.version")
    print_result("获取 json 配置值", result)

    # 4. 创建 text 文件
    text_name = "demo_text"
    print(f"创建 text 文件: {text_name}")
    result = run_secureconfig_command("create", text_name, "--type", "text", "--force")
    print_result("创建 text 文件", result)

    # 5. 保存明文内容到 text 文件（直接写入文件）
    text_path = os.path.join("configs", text_name + ".txt")
    with open(text_path, "w", encoding="utf-8") as f:
        f.write("Hello, SecureConfig!\n这是一个文本文件。")
    print(f"已写入明文内容到 {text_path}")

    # 6. 加密 text 文件
    print(f"加密 text 文件: {text_name}")
    result = run_secureconfig_command("encrypt", text_name, "--type", "text")
    print_result("加密 text 文件", result)

    # 7. 解密 text 文件
    print(f"解密 text 文件: {text_name}")
    result = run_secureconfig_command("decrypt", text_name, "--type", "text")
    print_result("解密 text 文件", result)

    # 8. 创建 binary 文件
    binary_name = "demo_bin"
    print(f"创建 binary 文件: {binary_name}")
    result = run_secureconfig_command("create", binary_name, "--type", "binary", "--force")
    print_result("创建 binary 文件", result)

    # 9. 保存明文内容到 binary 文件（写入二进制数据）
    binary_path = os.path.join("configs", binary_name + ".bin")
    with open(binary_path, "wb") as f:
        f.write(b"\x00\x01\x02\x03\x04\x05\x06\x07")
    print(f"已写入明文内容到 {binary_path}")

    # 10. 加密 binary 文件
    print(f"加密 binary 文件: {binary_name}")
    result = run_secureconfig_command("encrypt", binary_name, "--type", "binary")
    print_result("加密 binary 文件", result)

    # 11. 解密 binary 文件
    print(f"解密 binary 文件: {binary_name}")
    result = run_secureconfig_command("decrypt", binary_name, "--type", "binary")
    print_result("解密 binary 文件", result)

    print("\n===== 第二部分: 原地加解密操作 (使用 --inplace 参数) =====")

    # 12. 创建原地加密演示文件
    inplace_name = "inplace_demo"
    json_path = os.path.join("configs", inplace_name + ".json")
    backup_path = os.path.join("configs", inplace_name + "_backup.json")
    
    print(f"创建原地加密演示 json 文件: {inplace_name}")
    result = run_secureconfig_command("create", inplace_name, "--type", "json", "--force")
    print_result("创建原地加密演示文件", result)

    # 13. 设置演示文件内容
    print(f"设置演示文件值: {inplace_name}")
    result = run_secureconfig_command("set-value", inplace_name, "demo.name", "原地加密演示")
    result = run_secureconfig_command("set-value", inplace_name, "demo.description", "这是一个测试原地加密功能的文件")

    # 14. 解密后备份原始明文文件（用于对比）
    result = run_secureconfig_command("decrypt", inplace_name, "--type", "json")
    shutil.copy2(json_path, backup_path)
    print_result("设置演示文件值", result)
    print(f"已备份明文文件到 {backup_path}")

    # 15. 原地加密
    print(f"原地加密文件: {inplace_name} (使用 --inplace 参数)")
    result = run_secureconfig_command("encrypt", inplace_name, "--type", "json", "--inplace")
    print_result("原地加密", result)

    # 16. 验证原地加密结果
    encrypted_json_exists = os.path.exists(os.path.join("configs", inplace_name + ".json.enc"))
    print(f"加密文件 ({inplace_name}.json.enc) 是否存在? {encrypted_json_exists}")
    original_json_exists = os.path.exists(json_path)
    print(f"原始文件 ({inplace_name}.json) 是否存在? {original_json_exists} (原地加密，应该存在)")

    # 17. 原地解密
    print(f"原地解密文件: {inplace_name} (使用 --inplace 参数)")
    result = run_secureconfig_command("decrypt", inplace_name, "--type", "json", "--inplace")
    print_result("原地解密", result)

    # 18. 验证文件是否相同
    are_files_identical = False
    try:
        with open(json_path, "r", encoding="utf-8") as f1, open(backup_path, "r", encoding="utf-8") as f2:
            are_files_identical = f1.read() == f2.read()
    except Exception as e:
        print(f"比较文件时出错: {e}")
    
    print(f"原地加解密后的文件与原始文件是否相同? {are_files_identical}")

    # 19. 清理演示文件
    print("\n===== 清理演示文件 =====")
    files_to_delete = [json_name, text_name, binary_name, inplace_name]
    
    for name in files_to_delete:
        print(f"删除文件: {name}")
        result = run_secureconfig_command("delete", name, "--type", "json")
        
    if os.path.exists(backup_path):
        os.remove(backup_path)
        print(f"已删除备份文件: {backup_path}")

    # 20. 演示 get-value/set-value 仅支持 json 的限制
    print("\n===== 演示 get-value/set-value 仅支持 json 的限制 =====")
    
    print(f"尝试对 text 文件使用 get-value (应报错)")
    result = run_secureconfig_command("get-value", text_name, "app.version", "--type", "text")
    print_result("get-value 用于 text 类型", result)

    print(f"尝试对 binary 文件使用 get-value (应报错)")
    result = run_secureconfig_command("get-value", binary_name, "app.version", "--type", "binary")
    print_result("get-value 用于 binary 类型", result)

    total_end_time = time.time()
    print(f"\n全部演示完成，总耗时: {total_end_time - total_start_time:.2f} 秒")
